package com.cssw.fyzb.busi.api.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.busi.model.dto.UnionRegisterDto;
import com.cssw.fyzb.busi.service.acct.AcctService;
import com.cssw.fyzb.busi.service.user.DistrictService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.service.user.UserSourceService;
import com.cssw.fyzb.busi.util.*;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.model.vo.user.InviteCodeVo;
import com.cssw.fyzb.core.model.vo.user.LoginInfoVo;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.cache.CacheKeys.*;
import static com.cssw.fyzb.busi.util.Bizs.ERROR_VERIFY;

@Function(description = "联合注册增加密码", parameters = {
        @Parameter(name = "mobile", type = Type.String, description = "用户手机号", required = true),
        @Parameter(name = "loginPwd", type = Type.String, description = "登录密码", required = true),
        @Parameter(name = "inviteCode", type = Type.String, description = "邀请码", required = true),
})
@Component
public class UnionRegisterAddPwd implements Action {

    private static final Logger logger = LoggerFactory.getLogger(UnionRegisterAddPwd.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserSourceService userSourceService;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private AcctService acctService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    @Override
    public Response execute(Request request) throws Exception {
        String mobile = request.getString("mobile");
        String loginPwd = request.getString("loginPwd");
        String inviteCode = request.getString("inviteCode");

        SimpleLock simpleLock = simpleLockFactory.getLock("UNION_" + mobile);
        try {
            simpleLock.acquire();

            String cacheStr = simpleCache.get(forUnionRegisterPwd(mobile));
            if (StringUtil.isEmpty(cacheStr)) {
                return Response.fail("注册超时！");
            }
            if (StringUtil.isEmpty(inviteCode)){
                return Response.fail("请输入邀请码！");
            }

            Long supUserId = getSupUserId(inviteCode);
            User supUser = userService.getById(supUserId);

            //判断是否实名
            if (!User.FACE_AUTH_YES.equals(supUser.getFaceAuth())) {
                return Response.fail("推荐人未实名");
            }

            UnionRegisterDto dto = JSON.parseObject(cacheStr, UnionRegisterDto.class);

            UserSource openUserSource = userSourceService.getBySourceCode(dto.getSourceType(), dto.getOpenId());

            if (null != openUserSource) {
                return Response.fail("账号已经绑定用户，请重新登录！");
            }

            User mobileUser = userService.getByMobile(mobile);
            if (mobileUser == null){
                Long userId = userService.saveUnion(supUserId, mobile, dto.getSourceType(), dto.getOpenId(), dto.getNickName(), dto.getAvatar(), loginPwd);
                User user = userService.getById(userId);
                return Response.success().put("data", convert(user));
            } else {
                UserSource mobileUserSource = userSourceService.getBySourceCode(mobileUser.getUserId(),  dto.getSourceType());
                if (null != mobileUserSource && !dto.getOpenId().equals(mobileUserSource.getSourceCode())) {
                    return Response.fail("该手机号码已经绑定了其他账号");
                }

                //手机号码用户存在，且没有绑定唯一标识，则绑定信息并返回
                userSourceService.save(mobileUser.getUserId(), dto.getSourceType(), dto.getOpenId(), "");
                return Response.success().put("data", convert(mobileUser));
            }

        } catch (Exception e) {
            if (e instanceof BizException) {
                BizException se = (BizException) e;
                return Response.fail(se.getErrMsg(), se.getErrCode());
            }
            logger.error("", e);
            return Response.fail("用户注册失败");
        } finally {
            simpleLock.release();
        }
    }

    private Long getSupUserId(String inviteCode) {
        Long supUserId = null;
        try {
            if (StringUtils.isNotEmpty(inviteCode)) {
                supUserId = CodeUtil.decode(inviteCode);
                User inviter = userService.getById(supUserId);
                if (inviter == null) {
                    BizUtil.exception(Bizs.ERROR_INVITCODE);
                }
            } else {
                BizUtil.exception("必须输入邀请码");
            }
        } catch (Exception e){
            logger.error("", e);
            BizUtil.exception("邀请码不正确");
        }

        return supUserId;
    }


    private LoginInfoVo convert(User user) {
        LoginInfoVo vo = new LoginInfoVo();
        vo.setAvatar(user.getAvatar());
        vo.setAvatar_thumb(user.getAvatar());
        vo.setId(user.getUserId()); //用户标识
        vo.setUserId(user.getUserId()); //用户标识
        vo.setUser_nickname(user.getNickName());
        // 地区名称
        if (user.getDistrict() != null) {
            District district = districtService.getByCode(user.getDistrict());
            if (district != null) {
                vo.setArea(district.getDistrictName());
            }
        }
        // 城市名称
        if (user.getCity() != null) {
            District district = districtService.getByCode(user.getCity());
            if (district != null) {
                vo.setCity(district.getDistrictName());
            }
        }
        // 省
        if (user.getProvince() != null) {
            District district = districtService.getByCode(user.getProvince());
            if (district != null) {
                vo.setProvince(district.getDistrictName());
            }
        }

        vo.setAge(0);
        if (null != user.getBirthday()) {
            vo.setBirthday(TimeUtil.format(user.getBirthday(), "yyyy-MM-dd"));
        }

        vo.setCode(CodeUtil.encode(user.getUserId())); //邀请码

        Acct acct = acctService.queryAcctByUIdAndType(user.getUserId(), AcctType.ACCT_TYPE_F);
        if (null != acct) {
            vo.setCoin(acct.getBalanceFee().toString());//福币
        }

        vo.setHometown(""); //不确定是什么
        vo.setIsreg("0");//注册标识，不确定怎么用
        vo.setLast_login_time("");  //最后登录时间
        vo.setLogin_type("phone");  //登录类型

        vo.setMobile(user.getMobile());  //手机号码
        vo.setSex(user.getSex());

        vo.setSignature(user.getSign());
        vo.setFaceAuth(user.getFaceAuth());

        SimpleLock simpleLock = simpleLockFactory.getLock("USER_LOGIN_" + user.getUserId());
        try {
            simpleLock.acquire();
            String token = HashUtil.md5(user.getUserId() + "" + System.currentTimeMillis());
            CmfUserToken userToken = userService.getCmfTokenByUserId(user.getUserId());

            if (null == userToken) {
                userService.saveCmfToken(user.getUserId(), token);
            } else {
                userToken.setToken(token);
                //userToken.setExpireTime();
                userService.updateCmfToken(userToken);
            }

            //清除php侧的登录缓存
            simpleCache.delete("token_" + user.getUserId());

            vo.setToken(token);
        } catch (Exception e) {
            logger.error("", e);
            BizUtil.exception("");
        } finally {
            try {
                simpleLock.release();
            } catch (Exception e) {
                logger.error("", e);
            }
        }

        return vo;
    }
}
